package com.xuetang.controller.admin;

import com.xuetang.entity.*;
import com.xuetang.service.DietService;
import com.xuetang.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * 饮食管理后台控制器
 */
@RestController
@RequestMapping("/admin/diet")
public class DietManageController {

    @Autowired
    private DietService dietService;

    /**
     * 获取食物类别列表
     */
    @GetMapping("/categories")
    public Map<String, Object> getFoodCategories() {
        List<DietFoodCategory> categories = dietService.getFoodCategories();
        return ResultUtil.success(categories);
    }

    /**
     * 添加食物类别
     */
    @PostMapping("/categories")
    public Map<String, Object> addFoodCategory(@RequestBody DietFoodCategory category) {
        // 暂未实现，需要补充服务层方法
        return ResultUtil.error("功能尚未实现");
    }

    /**
     * 更新食物类别
     */
    @PutMapping("/categories/{id}")
    public Map<String, Object> updateFoodCategory(
            @PathVariable Integer id,
            @RequestBody DietFoodCategory category) {
        // 暂未实现，需要补充服务层方法
        return ResultUtil.error("功能尚未实现");
    }

    /**
     * 删除食物类别
     */
    @DeleteMapping("/categories/{id}")
    public Map<String, Object> deleteFoodCategory(@PathVariable Integer id) {
        // 暂未实现，需要补充服务层方法
        return ResultUtil.error("功能尚未实现");
    }

    /**
     * 获取食物列表
     */
    @GetMapping("/foods")
    public Map<String, Object> getFoods(
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result;
        if (keyword != null && !keyword.trim().isEmpty()) {
            result = dietService.searchFoods(keyword, page, pageSize);
        } else if (categoryId != null) {
            result = dietService.getFoodsByCategory(categoryId, page, pageSize);
        } else {
            // 暂时使用搜索空字符串代替获取所有
            result = dietService.searchFoods("", page, pageSize);
        }

        return ResultUtil.success(result);
    }

    /**
     * 获取食物详情
     */
    @GetMapping("/foods/{id}")
    public Map<String, Object> getFoodDetail(@PathVariable Integer id) {
        DietFood food = dietService.getFoodDetail(id);
        return ResultUtil.success(food);
    }

    /**
     * 添加食物
     */
    @PostMapping("/foods")
    public Map<String, Object> addFood(@RequestBody DietFood food) {
        boolean success = dietService.addFood(food);
        return success ? ResultUtil.success() : ResultUtil.error("添加食物失败");
    }

    /**
     * 更新食物
     */
    @PutMapping("/foods/{id}")
    public Map<String, Object> updateFood(
            @PathVariable Integer id,
            @RequestBody DietFood food) {
        food.setId(id);
        boolean success = dietService.updateFood(food);
        return success ? ResultUtil.success() : ResultUtil.error("更新食物失败");
    }

    /**
     * 删除食物
     */
    @DeleteMapping("/foods/{id}")
    public Map<String, Object> deleteFood(@PathVariable Integer id) {
        boolean success = dietService.deleteFood(id);
        return success ? ResultUtil.success() : ResultUtil.error("删除食物失败");
    }

    /**
     * 获取用户饮食记录列表
     */
    @GetMapping("/records")
    public Map<String, Object> getDietRecords(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {

        if (startDate == null) {
            // 默认为30天前
            startDate = new Date(System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000);
        }

        if (endDate == null) {
            // 默认为今天
            endDate = new Date();
        }

        Map<String, Object> result = dietService.getDietRecords(userId, startDate, endDate, page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 获取食谱列表
     */
    @GetMapping("/recipes")
    public Map<String, Object> getRecipes(
            @RequestParam(required = false) String mealType,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result;
        if (mealType != null && !mealType.trim().isEmpty()) {
            result = dietService.getRecipesByMealType(mealType, page, pageSize);
        } else {
            result = dietService.getRecommendRecipes(page, pageSize);
        }

        return ResultUtil.success(result);
    }

    /**
     * 获取食谱详情
     */
    @GetMapping("/recipes/{id}")
    public Map<String, Object> getRecipeDetail(@PathVariable Integer id) {
        DietRecipe recipe = dietService.getRecipeDetail(id);
        return ResultUtil.success(recipe);
    }

    /**
     * 添加食谱
     */
    @PostMapping("/recipes")
    public Map<String, Object> addRecipe(@RequestBody Map<String, Object> params) {
        try {
            // 参数校验
            if (params == null) {
                return ResultUtil.error("请求参数不能为空");
            }

            // 检查必要字段
            if (!params.containsKey("title") || params.get("title") == null ||
                    String.valueOf(params.get("title")).trim().isEmpty()) {
                return ResultUtil.error("食谱标题不能为空");
            }

            DietRecipe recipe = new DietRecipe();
            recipe.setTitle(String.valueOf(params.get("title")).trim());
            recipe.setDescription(params.containsKey("description") ? String.valueOf(params.get("description")) : "");
            recipe.setImage(params.containsKey("image") ? String.valueOf(params.get("image")) : "");
            recipe.setMealType(params.containsKey("mealType") ? String.valueOf(params.get("mealType")) : "");
            recipe.setTips(params.containsKey("tips") ? String.valueOf(params.get("tips")) : "");

            // 处理准备时间和烹饪时间
            if (params.containsKey("prepTime") && params.get("prepTime") != null) {
                try {
                    recipe.setPrepTime(Integer.parseInt(String.valueOf(params.get("prepTime"))));
                } catch (NumberFormatException e) {
                    recipe.setPrepTime(10); // 默认10分钟
                }
            } else {
                recipe.setPrepTime(10); // 默认10分钟
            }

            if (params.containsKey("cookTime") && params.get("cookTime") != null) {
                try {
                    recipe.setCookTime(Integer.parseInt(String.valueOf(params.get("cookTime"))));
                } catch (NumberFormatException e) {
                    recipe.setCookTime(20); // 默认20分钟
                }
            } else {
                recipe.setCookTime(20); // 默认20分钟
            }

            List<DietRecipeDetail> details = new ArrayList<>();
            if (params.containsKey("foods") && params.get("foods") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> foodsData = (List<Map<String, Object>>) params.get("foods");
                details = convertFoodsToRecipeDetails(foodsData);
            }

            // 处理烹饪步骤
            List<DietRecipeStep> steps = new ArrayList<>();
            if (params.containsKey("steps") && params.get("steps") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> stepsData = (List<Map<String, Object>>) params.get("steps");

                int stepOrder = 1;
                for (Map<String, Object> step : stepsData) {
                    if (step.containsKey("content")) {
                        DietRecipeStep recipeStep = new DietRecipeStep();
                        recipeStep.setContent(String.valueOf(step.get("content")));
                        recipeStep.setStepOrder(
                                step.containsKey("stepOrder") ? Integer.parseInt(String.valueOf(step.get("stepOrder")))
                                        : stepOrder++);
                        recipeStep.setImage(step.containsKey("image") ? String.valueOf(step.get("image")) : null);
                        steps.add(recipeStep);
                    }
                }
            }

            // 设置步骤
            recipe.setSteps(steps);

            boolean success = dietService.addRecipe(recipe, details);
            return success ? ResultUtil.success() : ResultUtil.error("添加食谱失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("添加食谱失败: " + e.getMessage());
        }
    }

    /**
     * 更新食谱
     */
    @PutMapping("/recipes/{id}")
    public Map<String, Object> updateRecipe(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> params) {
        try {
            // 参数校验
            if (params == null) {
                return ResultUtil.error("请求参数不能为空");
            }

            // 检查必要字段
            if (!params.containsKey("title") || params.get("title") == null ||
                    String.valueOf(params.get("title")).trim().isEmpty()) {
                return ResultUtil.error("食谱标题不能为空");
            }

            DietRecipe recipe = new DietRecipe();
            recipe.setId(id);
            recipe.setTitle(String.valueOf(params.get("title")).trim());
            recipe.setDescription(params.containsKey("description") ? String.valueOf(params.get("description")) : "");
            recipe.setImage(params.containsKey("image") ? String.valueOf(params.get("image")) : "");
            recipe.setMealType(params.containsKey("mealType") ? String.valueOf(params.get("mealType")) : "");
            recipe.setTips(params.containsKey("tips") ? String.valueOf(params.get("tips")) : "");

            // 处理准备时间和烹饪时间
            if (params.containsKey("prepTime") && params.get("prepTime") != null) {
                try {
                    recipe.setPrepTime(Integer.parseInt(String.valueOf(params.get("prepTime"))));
                } catch (NumberFormatException e) {
                    recipe.setPrepTime(10); // 默认10分钟
                }
            } else {
                recipe.setPrepTime(10); // 默认10分钟
            }

            if (params.containsKey("cookTime") && params.get("cookTime") != null) {
                try {
                    recipe.setCookTime(Integer.parseInt(String.valueOf(params.get("cookTime"))));
                } catch (NumberFormatException e) {
                    recipe.setCookTime(20); // 默认20分钟
                }
            } else {
                recipe.setCookTime(20); // 默认20分钟
            }

            List<DietRecipeDetail> details = new ArrayList<>();
            if (params.containsKey("foods") && params.get("foods") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> foodsData = (List<Map<String, Object>>) params.get("foods");
                details = convertFoodsToRecipeDetails(foodsData);
            }

            // 处理烹饪步骤
            List<DietRecipeStep> steps = new ArrayList<>();
            if (params.containsKey("steps") && params.get("steps") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> stepsData = (List<Map<String, Object>>) params.get("steps");

                int stepOrder = 1;
                for (Map<String, Object> step : stepsData) {
                    if (step.containsKey("content")) {
                        DietRecipeStep recipeStep = new DietRecipeStep();
                        recipeStep.setContent(String.valueOf(step.get("content")));
                        recipeStep.setStepOrder(
                                step.containsKey("stepOrder") ? Integer.parseInt(String.valueOf(step.get("stepOrder")))
                                        : stepOrder++);
                        recipeStep.setImage(step.containsKey("image") ? String.valueOf(step.get("image")) : null);
                        steps.add(recipeStep);
                    }
                }
            }

            // 设置步骤
            recipe.setSteps(steps);

            boolean success = dietService.updateRecipe(recipe, details);
            return success ? ResultUtil.success() : ResultUtil.error("更新食谱失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("更新食谱失败: " + e.getMessage());
        }
    }

    /**
     * 删除食谱
     */
    @DeleteMapping("/recipes/{id}")
    public Map<String, Object> deleteRecipe(@PathVariable Integer id) {
        boolean success = dietService.deleteRecipe(id);
        return success ? ResultUtil.success() : ResultUtil.error("删除食谱失败");
    }

    /**
     * 获取用户饮食统计数据
     */
    @GetMapping("/stats")
    public Map<String, Object> getDietStats(
            @RequestParam Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {

        if (startDate == null) {
            // 默认为30天前
            startDate = new Date(System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000);
        }

        if (endDate == null) {
            // 默认为今天
            endDate = new Date();
        }

        Map<String, Object> stats = dietService.getDietStats(userId, startDate, endDate);
        return ResultUtil.success(stats);
    }

    /**
     * 获取饮食管理仪表盘数据
     */
    @GetMapping("/dashboard")
    public Map<String, Object> getDashboard() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取食物总数
            int foodCount = dietService.countFoods();
            result.put("foodCount", foodCount);

            // 获取食谱总数
            int recipeCount = dietService.countRecipes();
            result.put("recipeCount", recipeCount);

            // 获取今日饮食记录数
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String todayStr = sdf.format(today);
            Date startOfDay = sdf.parse(todayStr);

            int todayRecordCount = dietService.countDietRecords(startOfDay, today);
            result.put("todayRecordCount", todayRecordCount);

            // 获取最近添加的食物
            List<DietFood> recentFoods = dietService.getRecentFoods(5);
            result.put("recentFoods", recentFoods);

            return ResultUtil.success(result);
        } catch (Exception e) {
            return ResultUtil.error("获取仪表盘数据失败: " + e.getMessage());
        }
    }

    /**
     * 将前端传入的食物数据转换为食谱明细对象
     */
    private List<DietRecipeDetail> convertFoodsToRecipeDetails(List<Map<String, Object>> foodsData) {
        List<DietRecipeDetail> details = new java.util.ArrayList<>();

        if (foodsData != null) {
            int sortOrder = 1;
            for (Map<String, Object> food : foodsData) {
                try {
                    // 跳过没有foodId的食材
                    if (!food.containsKey("foodId") || food.get("foodId") == null) {
                        continue;
                    }

                    DietRecipeDetail detail = new DietRecipeDetail();
                    detail.setFoodId(Integer.parseInt(String.valueOf(food.get("foodId"))));

                    // 处理数量
                    if (food.containsKey("quantity") && food.get("quantity") != null) {
                        try {
                            detail.setQuantity(new java.math.BigDecimal(String.valueOf(food.get("quantity"))));
                        } catch (NumberFormatException e) {
                            detail.setQuantity(new java.math.BigDecimal("100")); // 默认数量
                        }
                    } else {
                        detail.setQuantity(new java.math.BigDecimal("100")); // 默认数量
                    }

                    // 处理单位
                    detail.setUnit(
                            food.containsKey("unit") && food.get("unit") != null ? String.valueOf(food.get("unit"))
                                    : "g");

                    detail.setSortOrder(sortOrder++);
                    details.add(detail);
                } catch (Exception e) {
                    // 记录错误但继续处理其他食材
                    System.err.println("处理食材数据出错: " + e.getMessage());
                }
            }
        }

        return details;
    }

    /**
     * 删除饮食记录
     */
    @DeleteMapping("/records/{id}")
    public Map<String, Object> deleteDietRecord(@PathVariable Long id) {
        boolean success = dietService.deleteDietRecord(id);
        return success ? ResultUtil.success() : ResultUtil.error("删除饮食记录失败");
    }

    /**
     * 获取饮食记录详情
     */
    @GetMapping("/records/{id}")
    public Map<String, Object> getDietRecordDetail(@PathVariable Long id) {
        DietRecord record = dietService.getDietRecordById(id);
        if (record == null) {
            return ResultUtil.error("饮食记录不存在");
        }
        // 获取记录的明细
        List<DietRecordDetail> details = dietService.getDietRecordDetails(id);
        record.setMeals(details);
        return ResultUtil.success(record);
    }
}